//# sourceURL=http://uMapApp/Module/UavFlight/UavFlight
define([
    "mhjs/mhjs",
    "uMap/uMap",
    "uEarth/uEarth",
    "../../Earth/ViewPort"
], function (
    mhjs,
    uMap,
    uEarth,
    ViewPort
) {

    function UavFlight(option) {
        var _this = this;

        // http://218.94.153.70:48081/video/WTE/FHD/DJI_0003.json
        // "data" : {
        //     "positions" : [
        //         {
        //             "time"      : "2019-03-29 13:09:46.232",
        //             "latitude"  : "30.903267",
        //             "longitude" : "120.422720"
        //         },

        _this._positionSample = 200;
        _this._propertySample = 1;
        _this._pitch = 20;
        _this._range = 100;
        _this._baseHeight = 100;

        _this._positionTimes = [];
        _this._sampledPositions = [];

        _this.property = new uEarth.SampledPositionProperty();
        _this.property.setInterpolationOptions({
            interpolationDegree   : 3,
            interpolationAlgorithm: uEarth.HermitePolynomialApproximation
        });
        _this.path = new uMap.Entity();
        _this.entity = new uMap.Entity({
            "_objectOption": {
                position: _this.property
            }
        });

        _this.onStopListener = function () {
            _this.trigger("end");
            _this.app.earth.clock.onStop.removeEventListener(_this.onStopListener);
        };

        _this.onTickListener = function () {
            _this.updateCamera();
            _this.trigger("tick");
        };


        option && _this.OptionToProperties(option);
    }

    var _class = UavFlight;

    mhjs.OptionToPropertiesInterface(_class);
    mhjs.EventInterface(_class);

    Object.defineProperties(_class.prototype, {
        "load"                      : {
            value: function (callback) {
                var _this = this;
                if (!_this.isLoaded) {
                    if (_this.dataURL && _this.videoURL) {

                        $.get(_this.dataURL, function (json) {

                            if (json && json.code === 1) {

                                var positions = json.data.positions;


                                $.each(positions, function (i, position) {

                                    if (i === 0 || i % _this._positionSample === 0 || i === positions.length - 1) {

                                        var positionTime = {
                                            position: new uMap.Position({
                                                "latitude" : Number(position.latitude),
                                                "longitude": Number(position.longitude),
                                                "height"   : Number(position.height !== undefined ? position.height : _this._baseHeight)
                                            }),
                                            time    : uEarth.JulianDate.fromDate(new Date(position.time))
                                        };

                                        _this._positionTimes.push(positionTime);

                                        if (i === 0) {
                                            _this.startTime = positionTime.time;
                                        } else if (i === positions.length - 1) {
                                            _this.stopTime = positionTime.time;
                                        }

                                        _this.property.addSample(positionTime.time, positionTime.position.cartesian);

                                    }


                                });

                                _this.entity.availability = new uEarth.TimeIntervalCollection([new uEarth.TimeInterval({
                                    start: _this.startTime,
                                    stop : _this.stopTime
                                })]);

                                _this.entity.billboard = new uMap.BillboardGraphic({
                                    objectOption: {
                                        image                   : "./img/icon/iconLBS_02.png",
                                        pixelOffset             : [0, -10],
                                        distanceDisplayCondition: Number.POSITIVE_INFINITY
                                    }
                                }).object;

                                _this.entity.orientation = new uEarth.VelocityOrientationProperty(_this.property);

                                _this._sampledPositions.push(_this._positionTimes[0].position);

                                for (var i = 1; i < uEarth.JulianDate.secondsDifference(_this.stopTime, _this.startTime) / _this._propertySample; i++) {
                                    _this._sampledPositions.push(
                                        new uMap.Position(
                                            _this.property.getValue(
                                                uEarth.JulianDate.addSeconds(_this.startTime, i * _this._propertySample, new uEarth.JulianDate())
                                            )
                                        )
                                    );
                                }

                                _this._sampledPositions.push(_this._positionTimes[_this._positionTimes.length - 1].position);

                                _this.path.polyline = new uMap.PolylineGraphic({
                                    objectOption: {
                                        positions: _this._sampledPositions,
                                        color    : ["#ff0", 0.8],
                                        width    : 5
                                    }
                                }).object;

                                _this.isLoaded = true;
                                callback && callback();
                            }
                        });

                    }

                } else {
                    callback && callback();
                }
            }
        },
        "open"                      : {
            value: function (callback) {

                var _this = this;

                if (!_this.isOpened) {
                    _this.load(function () {
                        _this.path.show = true;
                        _this.entity.show = true;
                        _this.isOpened = true;
                        _this.trigger("open");
                        callback && callback();
                    });
                } else {
                    callback && callback();
                }

            }
        },
        "close"                     : {
            value: function () {
                var _this = this;
                if (_this.isOpened) {
                    _this.path.show = false;
                    _this.entity.show = false;
                    _this.app.earth.clock.onTick.removeEventListener(_this.onTickListener);
                    _this.app.earth.camera.lookAtTransform(uEarth.Matrix4.IDENTITY);
                    _this.isOpened = false;
                    _this.trigger("close");
                }
            }
        },
        "play"                      : {
            value: function () {
                var _this = this;

                _this.open(function () {
                    _this.active();
                    _this.app.earth.clock.shouldAnimate = true;
                    _this.app.earth.clock.onTick.addEventListener(_this.onTickListener);
                    _this.module.videoPlayer.video.play();
                    _this.isPlaying = true;
                    _this.trigger("play");
                    _this.trigger("toggle");

                });
            }
        },
        "pause"                     : {
            value: function () {
                var _this = this;
                _this.app.earth.clock.shouldAnimate = false;
                _this.app.earth.clock.onTick.removeEventListener(_this.onTickListener);
                _this.module.videoPlayer.video.pause();
                _this.isPlaying = false;
                _this.trigger("pause");
                _this.trigger("toggle");
            }
        },
        "toggle"                    : {
            value: function () {
                var _this = this;
                if (_this.isPlaying) {
                    _this.pause();
                } else {
                    _this.play();
                }
            }
        },
        "active"                    : {
            value: function () {
                var _this = this;

                if (_this.module.videoPlayer.source !== _this.videoURL) {

                    _this.app.earth.clock.currentTime = _this.startTime.clone();
                    _this.app.earth.clock.startTime = _this.startTime.clone();
                    _this.app.earth.clock.stopTime = _this.stopTime.clone();
                    _this.app.earth.clock.clockRange = uEarth.ClockRange.CLAMPED;
                    // _this.module.videoPlayer.title = uEarth.JulianDate.toDate(_this.startTime).format("yyyy/mm/dd");
                    _this.module.videoPlayer.source = _this.videoURL;
                    _this.updateCamera();
                    _this.app.earth.clock.onStop.addEventListener(_this.onStopListener);
                }

            }
        },
        "updateCamera"              : {
            value: function () {

                var _this = this;

                var position = new uMap.Position(_this.property.getValue(_this.app.earth.clock.currentTime));

                _this.app.earth.camera.viewBoundingSphere(
                    new uEarth.BoundingSphere(position.cartesian, 1),
                    new uEarth.HeadingPitchRange(
                        uEarth.Math.toRadians(_this.getSampledPositionsHeading()), // east, default value is 0.0 (north)
                        uEarth.Math.toRadians(-_this._pitch),
                        _this._range
                    )
                );
            }
        },
        "getSampledPositionsHeading": {
            value: function () {

                var _this = this;

                var heading;

                var currentPosition = _this.property.getValue(_this.app.earth.clock.currentTime);
                var previousPosition = _this.property.getValue(uEarth.JulianDate.addSeconds(_this.app.earth.clock.currentTime, -1, new uEarth.JulianDate()));
                var nextPosition = _this.property.getValue(uEarth.JulianDate.addSeconds(_this.app.earth.clock.currentTime, 1, new uEarth.JulianDate()));

                if (previousPosition || nextPosition) {

                    if (previousPosition) {
                        heading = uMap.Positions.getHeading(previousPosition, currentPosition);
                    } else {
                        heading = uMap.Positions.getHeading(currentPosition, nextPosition);
                    }

                }

                return heading;
            }
        }
    });

    return _class;

});